import router from './router'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import { tools } from 'crec-common'
import config from '@/config/defaultSettings'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import Cookie from 'js-cookie'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const allowList = ['login'] // no redirect allowList

if (window.__POWERED_BY_QIANKUN__) {
  router.beforeEach((to, from, next) => {
    NProgress.start() // start progress bar
    to.meta && typeof to.meta.title !== 'undefined' && tools.setDocumentTitle(`${i18nRender(to.meta.title)} - ${config.title}`)
    // if (to.path === defaultRoutePath) {
    //   return window.history.pushState(null, defaultRoutePath, defaultRoutePath)
    // }
    // 判断basePath，存在则是hash模式，需要变更路径
    if (from.meta.basePath && !to.path.includes(from.meta.basePath) && to.path.indexOf('/') === 0) {
      // const routes = router.getRoutes()
      next({
        path: from.meta.basePath + to.path,
        query: to.query,
        params: to.params
      })
      return
    }
    if (Cookie.get(ACCESS_TOKEN)) {
      NProgress.done()
      next()
    } else {
      console.log(to)
      if (allowList.includes(to.name)) {
        // 在免登录名单，直接进入
        next()
      } else {
        // token为空清除global内token数据，触发门户跳转到登录
        store.dispatch('Logout')
        NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      }
    }
  })
} else {
  router.beforeEach((to, from, next) => {
    NProgress.start() // start progress bar
    to.meta &&
      typeof to.meta.title !== 'undefined' &&
      tools.setDocumentTitle(`${i18nRender(to.meta.title)} - ${config.fatherTitle}`)
    /* has token */
    if (Cookie.get(ACCESS_TOKEN)) {
      if (!store.getters.userId) {
        if (store.getters.auth_pattern === 1) {
          // 获取用户信息
          store
            .dispatch('GetInfo')
            .then(() => {
              store.dispatch('GenerateRoutes')
            })
            .finally(() => {
              NProgress.done()
              delete to.query.code
              next()
            })
        } else if (store.getters.auth_pattern === 2) {
          store.dispatch('GetIdentities').then(() => {
            // 获取用户信息
            store.dispatch('GetInfo').then(() => {
              store.dispatch('GenerateRoutes')
            }).finally(() => {
              NProgress.done()
              delete to.query.code
              next()
            })
          })
        } else {
          console.error('未设定授权模式')
        }
      } else {
        NProgress.done()
        next()
      }
    } else {
      if (allowList.includes(to.name)) {
        // 在免登录名单，直接进入
        next()
      } else {
        // 独自运行需跳转登录
        // next({ path: loginRoutePath, query: { redirect: to.fullPath } })
        // 调试跳过
        if (window.sessionStorage.getItem('code')) {
          store
            .dispatch('GetACCESS_TOKEN')
            .then(() => {
              store
                .dispatch('GetInfo')
                .then(() => { })
                .finally(() => {
                  NProgress.done()
                  delete to.query.code
                  next(to)
                })
            })
            .catch(err => {
              if (err.response && err.response.status === 401) {
                setTimeout(() => {
                  store.dispatch('Logout')
                }, 1500)
              }
            })
            .finally(() => {
              delete to.query.code
            })
        } else {
          store.dispatch('Login')
        }
        // next()
        NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      }
    }
  })
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
